import React from 'react';
import { Row, Col, Card, Typography, Divider } from 'antd';
import { ArrowRightOutlined } from '@ant-design/icons';
import { OptimizationHighlight } from '../../services/api';
import SqlEditor from '../SqlEditor/SqlEditor';
import './SqlComparisonView.css';

const { Title, Text } = Typography;

interface SqlComparisonViewProps {
  originalSql: string;
  optimizedSql: string;
  highlights: OptimizationHighlight[];
}

const SqlComparisonView: React.FC<SqlComparisonViewProps> = ({
  originalSql,
  optimizedSql,
  highlights
}) => {
  const getHighlightMarkers = (isOriginal: boolean) => {
    if (!highlights || highlights.length === 0) return [];

    return highlights
      .filter(highlight => {
        // 对于原始SQL，显示删除和修改
        // 对于优化SQL，显示添加和修改
        if (isOriginal) {
          return highlight.type === 'deletion' || highlight.type === 'modification';
        } else {
          return highlight.type === 'addition' || highlight.type === 'modification';
        }
      })
      .map((highlight, index) => ({
        id: `highlight-${isOriginal ? 'orig' : 'opt'}-${index}`,
        startLineNumber: highlight.line,
        startColumn: highlight.column,
        endLineNumber: highlight.line,
        endColumn: highlight.column + highlight.length,
        message: highlight.description,
        severity: getHighlightSeverity(highlight.type),
        className: `highlight-${highlight.type}`
      }));
  };

  const getHighlightSeverity = (type: string): 'error' | 'warning' | 'info' | 'hint' => {
    switch (type) {
      case 'deletion':
        return 'warning';
      case 'addition':
        return 'info';
      case 'modification':
        return 'hint';
      default:
        return 'info';
    }
  };

  const renderHighlightLegend = () => {
    const hasHighlights = highlights && highlights.length > 0;
    if (!hasHighlights) return null;

    const typeStats = highlights.reduce((acc, highlight) => {
      acc[highlight.type] = (acc[highlight.type] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    return (
      <div className="highlight-legend">
        <Text type="secondary" style={{ fontSize: 12 }}>
          变更统计: 
        </Text>
        {Object.entries(typeStats).map(([type, count]) => (
          <span key={type} className={`legend-item legend-${type}`}>
            {getTypeDisplayName(type)}: {count}
          </span>
        ))}
      </div>
    );
  };

  const getTypeDisplayName = (type: string) => {
    switch (type) {
      case 'addition':
        return '新增';
      case 'deletion':
        return '删除';
      case 'modification':
        return '修改';
      default:
        return type;
    }
  };

  return (
    <div className="sql-comparison-view">
      <Title level={5}>
        SQL对比
        <ArrowRightOutlined style={{ margin: '0 12px', color: '#1890ff' }} />
      </Title>
      
      {renderHighlightLegend()}
      
      <Row gutter={16} style={{ marginTop: 16 }}>
        <Col span={12}>
          <Card 
            size="small" 
            title={
              <Text strong style={{ color: '#ff4d4f' }}>
                原始SQL
              </Text>
            }
            className="sql-card original-sql"
          >
            <SqlEditor
              value={originalSql}
              onChange={() => {}} // 只读
              height={300}
              theme="light"
              readOnly={true}
              markers={getHighlightMarkers(true)}
            />
          </Card>
        </Col>
        
        <Col span={12}>
          <Card 
            size="small" 
            title={
              <Text strong style={{ color: '#52c41a' }}>
                优化后SQL
              </Text>
            }
            className="sql-card optimized-sql"
          >
            <SqlEditor
              value={optimizedSql}
              onChange={() => {}} // 只读
              height={300}
              theme="light"
              readOnly={true}
              markers={getHighlightMarkers(false)}
            />
          </Card>
        </Col>
      </Row>

      {/* 变更详情 */}
      {highlights && highlights.length > 0 && (
        <div className="changes-detail" style={{ marginTop: 16 }}>
          <Divider orientation="left" style={{ fontSize: 14 }}>
            变更详情
          </Divider>
          <div className="changes-list">
            {highlights.map((highlight, index) => (
              <div key={index} className={`change-item change-${highlight.type}`}>
                <span className="change-type">
                  {getTypeDisplayName(highlight.type)}
                </span>
                <span className="change-location">
                  第{highlight.line}行，第{highlight.column}列
                </span>
                <span className="change-description">
                  {highlight.description}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default SqlComparisonView;